<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","scheme":"Pisces","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="集合概述，遍历方法">
<meta property="og:type" content="article">
<meta property="og:title" content="Java日拱一卒-day10">
<meta property="og:url" content="http://yoursite.com/2020/04/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day10/index.html">
<meta property="og:site_name" content="很惭愧，就做了一点微小的工作">
<meta property="og:description" content="集合概述，遍历方法">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://yoursite.com/2020/04/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day10/Collection.jpeg">
<meta property="og:image" content="http://yoursite.com/2020/04/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day10/Map.jpeg">
<meta property="article:published_time" content="2020-04-22T14:32:52.000Z">
<meta property="article:modified_time" content="2020-05-18T01:29:00.473Z">
<meta property="article:author" content="文予">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://yoursite.com/2020/04/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day10/Collection.jpeg">

<link rel="canonical" href="http://yoursite.com/2020/04/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day10/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Java日拱一卒-day10 | 很惭愧，就做了一点微小的工作</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">很惭愧，就做了一点微小的工作</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">念念不忘，必有回响</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/04/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day10/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/uploads/wenyu.png">
      <meta itemprop="name" content="文予">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="很惭愧，就做了一点微小的工作">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java日拱一卒-day10
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-04-22 22:32:52" itemprop="dateCreated datePublished" datetime="2020-04-22T22:32:52+08:00">2020-04-22</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-18 09:29:00" itemprop="dateModified" datetime="2020-05-18T09:29:00+08:00">2020-05-18</time>
              </span>

          
            <div class="post-description">集合概述，遍历方法</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="集合概述"><a href="#集合概述" class="headerlink" title="集合概述"></a>集合概述</h2><p>为了保存数量不确定的数据，以及保存具有映射关系的数据（或者说关联数组），Java提供了集合类，或者说容器类，位于<code>java.util</code>包下，包括常用的各种数据结构：<code>List</code>表、<code>Set</code>集合、<code>Map</code>映射等等。<br>Java的集合类主要由两个接口派生而出：<code>Collection</code>和<code>Map</code>，二者是Java集合框架的根接口，这两个接口又包含了一些子接口或实现类，下图为<code>Collection</code>接口、子接口及其实现类。</p>
<p><img src="/2020/04/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day10/Collection.jpeg" alt="Collection"></p>
<p><img src="/2020/04/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day10/Map.jpeg" alt="Map"></p>
<p>访问<code>List</code>集合的元素，可以直接根据元素索引访问；如果访问<code>Map</code>集合中的元素，可以根据每项元素的<code>key</code>来访问其<code>value</code>；如果访问<code>Set</code>集合中的元素，则只能根据元素本身来访问。</p>
<p>对于<code>Set</code>、<code>List</code>、<code>Queue</code>、<code>Map</code>四种集合，最常用的实现类分别是<code>HashSet</code>、<code>TreeSet</code>、<code>ArrayList</code>、<code>ArrayDeque</code>和<code>HashMap</code>、<code>TreeMap</code>等实现类</p>
<h2 id="Collection和Iterator接口"><a href="#Collection和Iterator接口" class="headerlink" title="Collection和Iterator接口"></a><code>Collection</code>和<code>Iterator</code>接口</h2><p><code>Collection</code>接口是<code>List</code>、<code>Set</code>和<code>Queue</code>的父接口，该接口里定义的方法也可用于<code>List</code>、<code>Set</code>和<code>Queue</code>集合。</p>
<ul>
<li><code>boolean add(Object o)</code>：向集合里添加一个元素。如果集合对象被改变了，返回<code>true</code></li>
<li><code>boolean addAll(Collection c)</code>：该方法把集合<code>c</code>里所有的元素添加到指定集合中，如果集合对象被改变了，返回<code>true</code></li>
<li><code>void clear()</code>：清除集合中所有元素</li>
<li><code>boolean contains(Object O)</code>：返回集合中是否包含指定元素</li>
<li><code>boolean containsAll(Collection c)</code>：返回集合中是否包含集合<code>c</code>的所有元素</li>
<li><code>boolean isEmpty()</code>：返回集合是否为空，集合长度为0时返回<code>true</code>，否则为<code>false</code></li>
<li><code>Iterator iterator()</code>：返回一个<code>Iterator</code>对象，用于遍历集合里的元素</li>
<li><code>boolean remove(Object o)</code>：删除集合中的指定元素<code>o</code>，包含一个或多个时，只删除第一个。该方法返回<code>true</code></li>
<li><code>boolean removeAll(Collection c)</code>：调用该方法的集合减集合<code>c</code>，如果删除了一个或一个以上的元素，返回<code>true</code></li>
<li><code>boolean retainAll(Collection c)</code>：把调用该方法的集合变为与集合<code>c</code>的交集，如果改变了调用该方法的集合，则返回<code>true</code></li>
<li><code>int size()</code>：返回集合内元素个数</li>
<li><code>Object[] toArray()</code>：把集合转为数组，集合元素转为对应的数组元素<br><code>Collection</code>的用法有：添加元素、删除元素、返回元素个数以及清空整个集合等。</li>
</ul>
<h2 id="使用Iterator遍历集合"><a href="#使用Iterator遍历集合" class="headerlink" title="使用Iterator遍历集合"></a>使用<code>Iterator</code>遍历集合</h2><p><code>Iterator</code>接口也是Java集合框架的成员，主要用于遍历<code>Collection</code>集合中的元素，<code>Iterator</code>对象也被称为迭代器。<code>Iterator</code>接口定义了如下4个方法。</p>
<ul>
<li><code>boolean hasNext()</code>：如果被迭代的集合元素还没有被遍历完，则返回<code>true</code></li>
<li><code>Object next()</code>：返回集合里下一个元素</li>
<li><code>void remove()</code>：删除即合理上一次<code>next</code>方法返回的元素</li>
<li><code>void forEachRemaining(Consumer action)</code>：该方法为<code>Java 8</code>中新增，可以使用<code>Lambda</code>表达式遍历元素</li>
</ul>
<p>示例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.Collection;</span><br><span class="line"><span class="keyword">import</span> java.util.HashSet;</span><br><span class="line"><span class="keyword">import</span> java.util.Iterator;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">IteratorTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Collection&lt;String&gt; books = <span class="keyword">new</span> HashSet&lt;String&gt;();</span><br><span class="line">        books.add(<span class="string">"数学分析"</span>);</span><br><span class="line">        books.add(<span class="string">"高等代数"</span>);</span><br><span class="line">        books.add(<span class="string">"离散数学"</span>);</span><br><span class="line">        <span class="comment">// 获取books集合对应的迭代器</span></span><br><span class="line">        Iterator it = books.iterator();</span><br><span class="line">        <span class="keyword">while</span> (it.hasNext()) &#123;</span><br><span class="line">            <span class="comment">// it.next()方法返回的是Object类型，需要强制类型转换</span></span><br><span class="line">            String book = (String) it.next();</span><br><span class="line">            System.out.println(book);</span><br><span class="line">            <span class="keyword">if</span> (books.equals(<span class="string">"数学分析"</span>)) &#123;</span><br><span class="line">                <span class="comment">// 从迭代器中删除上一次next()方法返回的元素</span></span><br><span class="line">                it.remove();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 对book变量赋值不会改变集合元素本身</span></span><br><span class="line">            book = <span class="string">"测试字符串"</span>; <span class="comment">// 1</span></span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(books);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>Iterator</code>仅用于遍历集合，本身并没有盛装对象的能力。需要一个被迭代的集合.</p>
<p><code>1</code>处代码对迭代变量<code>book</code>进行赋值，但并不影响集合<code>books</code>的内容。也就是说，使用<code>Iterator</code>对集合进行迭代时，并没有把集合元素本身传给迭代变量，而是把集合元素的值传给了迭代变量，使用修改迭代变量的值对集合元素本身没有任何影响。</p>
<p>另外，在使用<code>Iterator</code>迭代访问<code>Collection</code>集合元素时，<code>Collection</code>元素的内容不能被改变，只有通过<code>Iterator</code>的<code>remove()</code>方法删除上一次<code>next()</code>方法返回的集合元素才可以，否则会引发<code>java.util.ConcurrentModificationException</code>异常。</p>

    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/04/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day9/" rel="prev" title="Java日拱一卒-day9">
      <i class="fa fa-chevron-left"></i> Java日拱一卒-day9
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/04/24/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day11/" rel="next" title="Java日拱一卒-day11">
      Java日拱一卒-day11 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#集合概述"><span class="nav-number">1.</span> <span class="nav-text">集合概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Collection和Iterator接口"><span class="nav-number">2.</span> <span class="nav-text">Collection和Iterator接口</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用Iterator遍历集合"><span class="nav-number">3.</span> <span class="nav-text">使用Iterator遍历集合</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="文予"
      src="/uploads/wenyu.png">
  <p class="site-author-name" itemprop="name">文予</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">29</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">文予</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>


        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

</body>
</html>
